/**
 * The LoaderAnimation class creates and removes the loader animation.
 */
class com.yourdomain.spreadshop.gui.mod.lib.LoaderAnimation {

	// Stores the movie clip.
	private var _clip:MovieClip;

	// An array of loader segments.
	private var _segs:Array;

	// The number of segments.
	private static var _nSeg:Number = 16;

	// The starting delay - the number of frames to show while delaying.	private static var _nDelay:Number = 10;

	/**
	 * LoaderAnimation Constructor
	 */
	public function LoaderAnimation(
		mc_loader:MovieClip
	) {
		_clip = mc_loader;
		// Hides the loader movie clip.
		_clip._visible = false;		_clip._alpha = 0;
		// Setup loader value.
		setValue();
	}

	/**
	 * Creates the animation.
	 */
	private function createAnimation():Void {
		_clip.onEnterFrame = function():Void {
			if((this._alpha += 10) > 90) {
				this._alpha = 100;
				delete this.onEnterFrame;
			}
		};
		_segs = new Array();
		for(var i:Number = 0; i < _nSeg; i++) {
			if(i > 0) _clip.seg0.duplicateMovieClip("seg"+ i, i);
			var seg:MovieClip = _clip["seg"+ i];
			var k:Number = i + 1;
			seg.isLast = (k == _nSeg);
			seg.gotoAndPlay(k);
			seg._alpha = (k / _nSeg * 100) >> 0;
			_segs.push(seg);
		}
		_clip._visible = false;
		_segs[_nSeg - 1].delay = _nDelay;
		_segs[_nSeg - 1].onEnterFrame = function():Void {
			if(--this.delay < 0) {
				this._parent._visible = true;
				delete this.onEnterFrame;
			}
		};
		// Shows the loader.
		_clip._visible = true;
	}

	/**
	 * Removes the animation.
	 */
	private function removeAnimation():Void {
		setValue();
		_clip.onEnterFrame = function():Void {
			if((this._alpha -= 10) < 10) {
				this._alpha = 0;
				delete this.onEnterFrame;
			}
		};
		for(var i:Number = 0; i < _segs.length; i++) {
			var seg:MovieClip = _segs[i];
			seg.onEnterFrame = function():Void {
				if(this._currentframe == 1) {
					if(this.isLast) {
						this._parent._visible = false;
					}
					delete this.onEnterFrame;
					this.gotoAndStop(1);
					this.removeMovieClip();
				}
			};
		}
 	}

	/**
	 * Sets the percentage value.
	 */
	private function setValue(str:String):Void {
		var value:String;
		if(str == undefined || isNaN(str)) {
			value = "";
		} else {
			value = str +" %";
		}
		_clip.tf.text = value;
	};

}
